package collector

import (
	"context"
	"github.com/go-kit/kit/log"
	"github.com/go-redis/redis/v8"
	"github.com/prometheus/client_golang/prometheus"
)

// 持久性指标
// rdb_last_save_time 最后一次持久化保存磁盘的时间戳
// rdb_changes_since_last_save 自最后一次持久化依赖数据库的更改数
const (
	// Subsystem.
	persistence = "persistence"
	//
	rdbLastSaveTime         = "rdb_last_save_time"
	rdbChangesSinceLastSave = "rdb_changes_since_last_save"
)

// Metric descriptors.
var (
	rdbLastSaveTimeDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, persistence, rdbLastSaveTime),
		"上次成功保存RDB的基于纪年的时间戳",
		[]string{}, nil,
	)
	rdbChangesSinceLastSaveDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, persistence, rdbChangesSinceLastSave),
		"自上次转储以来的更改次数",
		[]string{}, nil,
	)
)

// ScrapePersistence collects from performance.
type ScrapePersistence struct{}

// Name of the Scraper. Should be unique.
func (ScrapePersistence) Name() string {
	return persistence
}

// Help describes the role of the Scraper.
func (ScrapePersistence) Help() string {
	return "Collect the current size of all registered binlog files"
}

// Version of Redis from which scraper is available.
func (ScrapePersistence) Version() float64 {
	return 4.0
}

// Scrape collects data from redis connection and sends it over channel as prometheus metric.
func (ScrapePersistence) Scrape(ctx context.Context, client *redis.Client, ch chan<- prometheus.Metric, logger log.Logger) error {

	data, err := infos(client, "persistence", "stats")
	if err != nil {
		return err
	}

	lst := valueOf(data, rdbLastSaveTime)
	sls := valueOf(data, rdbChangesSinceLastSave)

	ch <- prometheus.MustNewConstMetric(
		rdbLastSaveTimeDesc, prometheus.GaugeValue, lst,
	)

	ch <- prometheus.MustNewConstMetric(
		rdbChangesSinceLastSaveDesc, prometheus.GaugeValue, sls,
	)

	return nil
}

// check interface
var _ Scraper = ScrapePersistence{}
